import random
import time

import redis
from connect_to_redis import BaseRedisConnection
from threading import Thread


class QueeueThread(Thread):
    
    def __init__(self,connection,team_name,max_count=1000,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.conn = connection
        self.key = team_name
        self.max_count = max_count

    def run(self):
        i = 1
        while i <= self.max_count:
            member = f'{self.name}_{i}'
            print(member)
            self.conn.rpush(self.key,member)
            i += 1
            time.sleep(random.random())




# lpush/rpush:从左/右插入数据
# lrange：获取指定长度的数据
# ltrim:截取一定长度的数据
# lpop/rpop:移除最左/右的成员并返回
# lpushx/rpushx:key存在的时候才插入数据，不存在是不做任何处理

class TestList(BaseRedisConnection):
    def test_push(self):
        # lpush/rpush:从左/右插入数据
        t = ['Amy','Bob']
        result = self.conn.lpush('user_list',*t)
        # self.conn.lpush('user_list','Amy','Bob')
        print(result)
        user_list = self.conn.lrange('user_list',0,-1)
        print(user_list)

    def test_pop(self):
        # lpop/rpop:移除最左/右的成员并返回
        result = self.conn.lpop('user_list')
        print(result)
        user_list = self.conn.lrange('user_list', 0, -1)
        print(user_list)

    def test_llen(self):
        # 列表长度
        result = self.conn.llen('user_list')
        print(result)

    # 使用多线程模拟用户抢购排队的功能
    def queeue_up(self):
        # 模拟排队
        team_name = 'team'
        self.conn.delete(team_name)
        t1 = QueeueThread(name='T1',connection=self.conn,team_name=team_name,max_count=1000)
        t2 = QueeueThread(name='T2',connection=self.conn,team_name=team_name,max_count=1000)
        t3 = QueeueThread(name='T3',connection=self.conn,team_name=team_name,max_count=1000)
        t1.start()
        t2.start()
        t3.start()
        # 等待三个线程处理完成，然后进行统计
        t1.join()
        t2.join()
        t3.join()
        print("llen",self.conn.llen(team_name))


def main():
    str_obj = TestList()
    # str_obj.test_push()
    # str_obj.test_pop()
    # str_obj.test_llen()
    str_obj.queeue_up()



if __name__ == '__main__':
    main()